package eu.dicodeproject.analysis.hbase;


import org.apache.hadoop.fs.Path;
import org.apache.hadoop.util.ToolRunner;
import org.apache.lucene.analysis.Analyzer;
import org.apache.mahout.common.AbstractJob;
import org.apache.mahout.common.commandline.DefaultOptionCreator;
import org.apache.mahout.vectorizer.DefaultAnalyzer;
import org.apache.mahout.vectorizer.DocumentProcessor;

import java.util.Map;

/**
 * Reads text from a configurable HBase table and column, tokenizes with Lucene and writes the resulting
 * tokenized stuff to HDFS for further processing by the Mahout colloc driver.
 */
public class HBaseLuceneTokenizerDriver extends AbstractJob {


  private HBaseLuceneTokenizerDriver() {
    // don't instantiate drivers
  }

  public static void main(String args[]) throws Exception {
    ToolRunner.run(new HBaseLuceneTokenizerDriver(), args);
  }

  @Override
  public int run(String[] args) throws Exception {
    addOutputOption();
    addOption(DefaultOptionCreator.numReducersOption().create());
    addOption("analyzerName", "a", "The class name of the analyzer to use for preprocessing", null);
    addOption("table", "t", "The hbase table holding our data.", "twittertracker");
    addOption("family", "f", "The column family holding our data.", "textFamily");
    addOption("column", "c", "The column holding our data.", "text");

    Map<String, String> argMap = parseArguments(args);
    if (argMap == null) {
      return -1;
    }

    Class<? extends Analyzer> analyzerClass = DefaultAnalyzer.class;
    if (argMap.get("--analyzerName") != null) {
      String className = argMap.get("--analyzerName");
      analyzerClass = Class.forName(className).asSubclass(Analyzer.class);
      // try instantiating it, b/c there isn't any point in setting it if
      // you can't instantiate it
      analyzerClass.newInstance();
    }
    String table = argMap.get("--table");
    String family = argMap.get("--family");
    String column = argMap.get("--column");

    Path output = getOutputPath();
    Path tokenizedPath = new Path(output, DocumentProcessor.TOKENIZED_DOCUMENT_OUTPUT_FOLDER);
    HBaseDocumentProcessor.tokenizeDocuments(table, family, column, analyzerClass, tokenizedPath);
    return 0;
  }

}
